# -*- coding:UTF-8 -*-
from django.contrib import admin
from AppModel.models import *
from AppModel.zySDK import zySDK
#from import_export import resources
from import_export.admin import ImportExportModelAdmin, ImportExportActionModelAdmin, ExportActionModelAdmin
import logging,json,datetime
from django.utils.html import format_html
from django.urls import reverse
from django import forms
from mptt.admin import MPTTModelAdmin
from mptt.admin import DraggableMPTTAdmin
from feincms.module.page.models import Page
#from django.utils.html import format_html,escape, mark_safe
from django.utils.safestring import mark_safe
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
import time
import decimal
from datetime import datetime
import os,qrcode
from import_export.tmp_storages import CacheStorage
from  .resource import UserInfoResource
from import_export import resources, fields
import tablib
from django.db.models import Max
from PIL import Image, ImageDraw, ImageFont
from ckeditor.widgets import CKEditorWidget
from django.db import connection


logger = logging.getLogger(__name__)
logger.setLevel(level = logging.DEBUG)
handler = logging.FileHandler("./bedrockapp.log")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# 公司管理
@admin.register(CompanyInfo)
class CompanyInfoAdmin(ImportExportModelAdmin): 
    list_display=['company_name','company_address','company_connect','company_phone','company_desc','qrcode_image','qrcode_url']
    search_fields =('company_name','company_address','company_connect','company_phone','company_desc','qrcode_image','qrcode_url')
    fieldsets = [
       ('用户数据', {'fields': ['company_name','company_address','company_connect','company_phone','company_desc','qrcode_image','qrcode_url'], 'classes': ['']}),
    ]
    actions = ["create_qrcode"]
    backMode = {  # 背景图属性，我的背景图上需要添加一个二维码和多个文本框
    "back_url": "bj3.jpg",  # 读取图片路径
    "size": (550, 363),  # 图片大小
    "QR": {  # 二维码属性
        "frame": (250, 263),  # 大小
        "position": (30, 30),  # 位置
    },
    "text": [{  # 文本框属性
        "size": 25,  # 字号
        # "ttf": "FZXBSJW.TTF",  # 字体
        "ttf": "pfh.ttf",  # 字体
        "color": "",  # 颜色
        "position": (150, 650),  # 文字位置
        "frame": (550, 50),
    }, {
        "size": 25,
        "ttf": "pfh.ttf",
        "color": "",
        "position": (200, 680),
        "frame": (550, 50),
    }, ],
    }

    def create_qrcode(self, request, queryset):
        cmp_list = CompanyInfo.objects.all()
        for cmp_info in cmp_list:
            img_path = os.path.split(os.path.realpath(__file__))[0]+"/../media/qrcode_image/"+cmp_info.company_name+".jpg"
            #qrcode.make("https://brilliantlife.com.cn:8090/media/qrcode/pages/index/index/"+str(cmp_info.id)).save(img_path)
            #cmp_info.qrcode_image = "qrcode_image/"+cmp_info.company_name+".jpg"
            cmp_info.qrcode_image = "qrcode_image/"+cmp_info.company_name+".jpg"
            #data = "https://brilliantlife.com.cn:8090/media/qrcode/pages/index/new_index/5092"
            data = "https://brilliantlife.com.cn:8090/media/qrcode/pages/index/index/"+str(cmp_info.id)
            text = "%s \n活动专属二维码" % (cmp_info.company_name)
            img = self.generate_qrcode_with_text(data, text,self.backMode)

            # 保存生成的二维码图像
            img.save(img_path)
            cmp_info.save()
            

    create_qrcode.short_description = "更新二维码"
    list_per_page = 15

    def generate_qrcode_with_text(self,data, text,mode):
    # 生成二维码图像
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=15,
            border=9,
        )
        qr.add_data(data)
        qr.make(fit=True)
        qr_img = qr.make_image(fill_color="black", back_color="white")
    
        # 添加文字
        draw = ImageDraw.Draw(qr_img)
        #font = ImageFont.truetype("/Library/Fonts/Microsoft/Microsoft Yahei.ttf", 35)  # 指定字体和字号
        #font = ImageFont.load_default()
        self.write_text(qr_img, text, mode["text"])
        #draw.text((30, qr_img.size[1] - 30), text, fill='black', font=font)  # 在二维码底部添加文字
    
        return qr_img
    
    def write_line(self,backimg, text, tmode):  # 给单个文本框填充数据
        #myfont = ImageFont.truetype("/Library/Fonts/Microsoft/Microsoft Yahei.ttf", size=30)
        myfont = ImageFont.truetype("/usr/share/fonts/google-droid/DroidSansFallback.ttf", size=24)
        draw = ImageDraw.Draw(backimg)
        tend = len(text)
        while True:
            text_size = draw.textsize(text[:tend], font=myfont)  # 文本图层的尺寸
            # print(text_size)
            if text_size[0] <= tmode["frame"][0]:
                break
            else:
                tend -= 1  # 文本太长，调整文本长度
        draw.text((tmode["position"][0], tmode["position"][1]), text[:tend], font=myfont)
    
        return backimg, tend


    def write_text(self,img, text, tmodeList):  # 写文本
        tlist = text.split("\n")
        mnum = 0
        draw = ImageDraw.Draw(img)
        for t in tlist:
            tbegin = 0
            tend = len(t)
            while True:
                img, tend = self.write_line(img, t[tbegin:tend], tmodeList[mnum])
                mnum += 1
                if tbegin + tend == len(t) or mnum == len(tmodeList):
                    break
                else:
                    tbegin = tbegin + tend
                    tend = len(t)
            if mnum == len(tmodeList):
                break
        return img
    


# 用户管理
@admin.register(UserInfo)
class UserInfoAdmin(ImportExportModelAdmin):
    tmp_storage_class = CacheStorage
    resource_class = UserInfoResource
    list_display=['user_name','weixin_openid','id_card','phone_number','company_name','labour_union','join_union','desc']
    search_fields = ('user_name','weixin_openid','id_card','phone_number','company_name','labour_union','join_union','desc')
    fieldsets = [
       ('用户数据', {'fields': ['user_name','weixin_openid','id_card','phone_number','company_name','labour_union','join_union','desc'], 'classes': ['']}),
    ]
    list_per_page = 15

    actions = ["execute_custom_sql"]
    def execute_custom_sql(self, request, queryset):
        with connection.cursor() as cursor:
            # 这里执行你的自定义 SQL 语句
            delete_sql = """ DELETE FROM appmodel_userinfo WHERE id NOT IN (SELECT id 
                          FROM ( SELECT id, ROW_NUMBER() OVER (PARTITION BY phone_number  
                          ORDER BY join_union DESC) AS row_num FROM appmodel_userinfo) AS subquery 
                          WHERE row_num = 1 );"""
            cursor.execute(delete_sql)
    execute_custom_sql.short_description = "删除冗余用户"


# 奖品管理
@admin.register(AwardInfo)
class AwardInfoAdmin(ImportExportModelAdmin): 
    list_display=['award_name','award_image','award_num','action_name']
    search_fields =('award_name','award_image','award_num','action_name')
    fieldsets = [
       ('用户数据', {'fields': ['award_name','award_image','award_num','action_name'], 'classes': ['']}),
    ]
    list_per_page = 15 
    autocomplete_fields = ('action_name',)


# 抽奖管理
@admin.register(PrizeInfo)
class PrizeInfoAdmin(ImportExportModelAdmin): 
    list_display=['prize_name','prize_image','current_remind_num','prize_probability']
    search_fields =('prize_name','prize_image','current_remind_num','prize_probability')
    fieldsets = [
       ('用户数据', {'fields': ['prize_name','prize_image','current_remind_num','prize_probability'], 'classes': ['']}),
    ]
    list_per_page = 15 


# 中奖管理
@admin.register(UserPrizeInfo)
class UserPrizeInfoAdmin(ImportExportModelAdmin): 
    list_display=['user_name','phone_number','labour_name','company_name','company_address','award_name','revice_time','is_prized','award_image']
    search_fields =('user_name','phone_number','labour_name','company_name','company_address','award_name','revice_time','is_prized')
    list_filter = ('is_prized',)
    fieldsets = [
       ('用户数据', {'fields': ['user_name','phone_number','labour_name','company_name','company_address','award_name','revice_time','is_prized','award_image'], 'classes': ['']}),
    ]
    actions = ["delete_large_amount_of_data"]

    def delete_large_amount_of_data(self, request, queryset):
        max_id = queryset.aggregate(Max('pk'))['pk__max']
        # 确定删除的批次大小
        batch_size = 1000

        # 循环遍历查询集，并按批次删除
        while max_id:
            queryset.filter(pk__lte=max_id).delete()
            max_id = queryset.aggregate(Max('pk'))['pk__max']

    delete_large_amount_of_data.short_description = "批量删除"
    list_per_page = 15 


# 题库管理
@admin.register(QuestionBank)
class QuestionBankAdmin(ImportExportModelAdmin): 
    list_display=['title','qtype','a','b','c','d','e','answer','score']
    search_fields =('title','qtype','a','b','c','d','e','answer','score')
    fieldsets = [
       ('用户数据', {'fields': ['title','qtype','a','b','c','d','e','answer','score'], 'classes': ['']}),
    ]
    list_per_page = 15 

# 考卷管理
@admin.register(TestPaperInfo)
class TestPaperInfoAdmin(admin.ModelAdmin): 
    list_display=['title','starttime','endtime','examtime','is_use','target_content']
    search_fields =('title','starttime','endtime','examtime','is_use','target_content')
    fieldsets = [
       ('用户数据', {'fields': ['title','starttime','endtime','examtime','pid','is_use','target_content'], 'classes': ['']}),
    ]
    list_per_page = 15
    filter_horizontal = ('pid',)

# 员工成绩管理
@admin.register(ExamScore)
class ExamScoreAdmin(ImportExportModelAdmin): 
    list_display=['user_name','phone_number','company_name','score','right_num','wrong_num','create_time']
    search_fields =('user_name','phone_number','company_name','score','right_num','wrong_num','create_time')
    fieldsets = [
       ('用户数据', {'fields': ['user_name','phone_number','company_name','score','right_num','wrong_num'], 'classes': ['']}),
    ]
    actions = ["delete_large_amount_of_data"]

    def delete_large_amount_of_data(self, request, queryset):
        max_id = queryset.aggregate(Max('pk'))['pk__max']
        # 确定删除的批次大小
        batch_size = 1000

        # 循环遍历查询集，并按批次删除
        while max_id:
            queryset.filter(pk__lte=max_id).delete()
            max_id = queryset.aggregate(Max('pk'))['pk__max']

    delete_large_amount_of_data.short_description = "批量删除成绩"
    list_per_page = 15


@admin.register(ActionInfo)
class ActionInfoAdmin(admin.ModelAdmin): 
    list_display=['action_name','start_time','end_time','active_long','testpaper','current_award_total','award_total_num','current_remind_num','choose_method','xcby','tsby','action_img','is_use','created_at','article_url','short_content']
    search_fields =('action_name','start_time','end_time','active_long','current_award_total','award_total_num','current_remind_num','is_use')
    fieldsets = [
       ('用户数据', {'fields': ['action_name','start_time','end_time','active_long','testpaper','current_award_total','award_total_num','current_remind_num','choose_method','xcby','tsby','action_img','is_use','created_at','article_url','content'], 'classes': ['']}),
    ]
    list_per_page = 15

    # raw_id_fields = ('testpaper',)
    autocomplete_fields = ('testpaper',)
    # list_editable = ('testpaper',)
    formfield_overrides = {
        models.TextField: {'widget': CKEditorWidget}
    }

    def short_content(self, obj):
        if len(obj.content) > 50:
            content_preview = f"{obj.content[:50]}..."
        else:
            content_preview = obj.content
        article_url = reverse('admin:AppModel_actioninfo_change', args=[obj.pk])
        #return format_html('<a href="{}">{}</a>', article_url, content_preview)
        return format_html('<div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><a href="{}">{}</a></div>',article_url, content_preview)
    short_content.short_description = '活动信息'



# 领奖管理
@admin.register(UserAward)
class UserAwardAdmin(ImportExportModelAdmin): 
    list_display=['user_name','phone_number','labour_name','company_name','company_address','is_finished','award_name','revice_time',"award_image"]
    search_fields =('user_name','phone_number','labour_name','company_name','company_address','is_finished','award_name','revice_time',"award_image")
    fieldsets = [
       ('用户数据', {'fields': ['user_name','phone_number','labour_name','company_name','company_address','is_finished','award_name','revice_time',"award_image"], 'classes': ['']}),
    ]
    list_per_page = 15


# 登录管理
@admin.register(WeixinAppLogin)
class WeixinAppLoginAdmin(admin.ModelAdmin): 
    list_display=['weixin_openid','weixin_sessionkey','update_time','phone_number','is_login']
    search_fields =('weixin_openid','weixin_sessionkey','update_time','phone_number','is_login')
    fieldsets = [
       ('用户数据', {'fields': ['weixin_openid','weixin_sessionkey','update_time','phone_number','is_login'], 'classes': ['']}),
    ]
    list_per_page = 15

     



# 领奖管理
@admin.register(GlobalSettings)
class GlobalSettingsAdmin(ImportExportModelAdmin):
    list_display=['choose_method','xcby']
    search_fields =('choose_method','xcby')
    fieldsets = [
       ('用户数据', {'fields': ['choose_method','xcby'], 'classes': ['']}),
    ]
    list_per_page = 15




admin.site.site_title = "泰达智慧群团"
admin.site.site_header = "泰达智慧群团2.0.1"



